import React, { Component } from "react";
import "../styles/comment.css";

class Comment extends Component {
  constructor(props) {
    super(props);
    this.state = {
      timeString: ""
    };
  }

  componentWillMount() {
    this._updateTimeString();
    this._timer = setInterval(this._updateTimeString.bind(this), 5000);
  }

  componentWillUnmount() {
    clearInterval(this._timer);
  }

  _updateTimeString() {
    const { comment } = this.props;
    const duration = (+Date.now() - comment.createdTime) / 1000;
    this.setState({
      timeString:
        duration > 60
          ? `${Math.round(duration / 60)} 分钟前`
          : `${Math.round(Math.max(duration, 1))} 秒前`
    });
  }

  handleDeleteComment() {
    if (this.props.onDeleteComment)
      this.props.onDeleteComment(this.props.index);
  }

  render() {
    const { comment } = this.props;
    return (
      <div className="list-item">
        <div className="list-figure" />
        <div className="list-username">{comment.username}:</div>
        <div className="list-content">{comment.content}</div>
        <div className="list-time">{this.state.timeString}</div>
        <div
          className="list-delete"
          onClick={this.handleDeleteComment.bind(this)}
        >
          删除
        </div>
      </div>
    );
  }
}

export default Comment;
